// 购物车相关
import { useStore } from 'vuex'
import { computed } from 'vue'
export const useCommonCartEffect = (shopId) => {
  const store = useStore()
  const cartList = store.state.cartList
  const changeCartItemInfo = (shopId, productId, productInfo, num) => {
    store.commit('changeCartItemInfo', { shopId, productId, productInfo, num })
  }
  // 购物车弹层数据
  const productList = computed(() => {
    const productList = cartList[shopId]?.productList || {}
    const notEmptyProductList = {}
    for (let i in productList) {
      if (productList[i].count > 0) {
        notEmptyProductList[i] = productList[i]
      }
    }
    return notEmptyProductList
  })
  const shopName = computed(() => {
    const shopName = cartList[shopId]?.shopName || ''
    return shopName
  })
  const calculations = computed(() => {
    const productList = cartList[shopId]?.productList
    const result = { total: 0, price: 0, allChecked: true }

    if (productList) {
      for (let i in productList) {
        result.total += productList[i].count
        if (productList[i].check) {
          result.price += productList[i].count * productList[i].price
        }
        // 如果count大于0并且未选中的情况下（也就是未全部选中的情况）
        if (productList[i].count > 0 && !productList[i].check) {
          result.allChecked = false
        }
      }
    }
    result.price = result.price.toFixed(2)
    return result
  })
  return { cartList, productList, calculations, shopName, changeCartItemInfo }
}
